/**
 * 游龙[Youlong]
 * @description 一个HTML转image的客户端服务
 * @author Veris
 * @date 2018-11-09
 * @version 0.1
 */
function Youlong(){
    // 处理队列
    var _processQueue = [];
    var _callback;
    var _socket;

    // 线程数
    this.threadNum = 10;
    // 渲染模式 [iframe]框架渲染 [div]DIV直接渲染
    this.mode='iframe';

    this.init = function(){
        var _this=this;
        console.log('初始化进程池...');
        // 初始化进程池
        for(var i=0; i<this.threadNum; i++){
            if(this.mode=='iframe'){
                $('#threads').append('<iframe id="thread_'+ i +'" class="thread" data-name="" data-status="0" width="150" height="150" src="" frameborder="0" scrolling="no"></iframe>');
            }else{
                $('#threads').append('<div id="thread_'+ i +'" class="thread" data-name="" data-status="0" scrolling="no"></div>');
            }
            var thread=document.getElementById('thread_'+i);
            thread.onload=function(){
                _this.render(this);
            };
        }
    }
    this.init();

    this.callback = function(callback){
        _callback=callback;
    }

    this.bind = function(address){
        return _socket = io(address);
    }

    this.listen = function(){
        console.log('开始监听...');
        var _this=this;
        _socket.on('connect', function(){
            console.log('connect success');
        });

        _socket.on('newTask', function(res){
            var data=JSON.parse(res);
            console.log('接收到队列',data);
            for(var i in data){
                var task=data[i];
                _processQueue.unshift({
                    name   :task.name,
                    address:task.address,
                });
            }
        });

        setInterval(function(){
            _this.runQueue();
        },1000);
    }

    this.runQueue = function(){
        var n=$('.thread[data-status="0"]').length;
        for(var i=0; i<n; i++){
            var task=_processQueue.pop();
            if(task){
                var res=this.loadHTML(task.name,task.address);
                // console.log(res);
                // 如果没有可用线程，则加回队列
                if(!res){
                    _processQueue.unshift(task);
                }
            }
        }
    }

    this.loadHTML = function(name,address){
        var _thread=$('.thread[data-status="0"]:first');
        if(_thread.length){
            _thread.attr('data-status',1);
            _thread.attr('data-name',name);
            if(this.mode=='iframe'){
                _thread.attr('src',"php/iframe.php?url="+address);;
            }else{
                _thread.empty();
                _thread.append(address);
                this.render(_thread[0])
            }
            return true;
        }
        return false;
    }

    this.render = function(_thread){
        var _this=this;

        if(this.mode=='iframe'){
            var d=_thread.contentWindow.document.body;
        }else{
            var d=_thread;
        }
        html2canvas(d,{
            scale:1
        }).then(function(canvas) {
            var name=_thread.getAttribute('data-name');
            var img=canvas.toDataURL("image/png");
            if(typeof _callback == 'function'){
                // 1.如果是函数则回调函数
                _callback(name,img);
                _thread.setAttribute('data-name','');
                _thread.setAttribute('data-status',0);
                return true;
            }else if(typeof _callback == 'object'){
                // 1.如果是函数则回调函数
                _callback.emit('imgCallback',JSON.stringify({
                    name:name,
                    img:img
                }));
                _thread.setAttribute('data-name','');
                _thread.setAttribute('data-status',0);
                return true;
            }else{
                // 2.如果是地址则用POST回调通知
                _this.http_post(_callback,{
                    name:name,
                    img:img
                },function(res){
                    _thread.setAttribute('data-name','');
                    _thread.setAttribute('data-status',0);
                    return true;
                });
            }
            console.log('线程 [ ' + _thread.id + ' ]','处理完毕 [ ' + name + ' ]');
        });
    }

    /**
     * http请求
     * @param string action 请求地址
     * @param array params 请求参数
     * @param function callback 回调函数
     * @return string 返回数据
     */
    this.http_post = function(url,params,callback,async=true)
    {
        $.ajax({
            url:url,
            type:'POST',
            data:params,
            timeout : 3000,
            dataType:'json',
            async:async,
            success:function(res){
                callback(res);
            },
            error:function(res){
                callback(res);
            },
        });
    }
}
